package com.resou.reader.bookshelf.readhistory;

import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.LayerDrawable;
import android.media.Image;
import android.os.Build;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.constraint.ConstraintLayout;
import android.support.graphics.drawable.VectorDrawableCompat;
import android.support.v7.app.ActionBar;
import android.support.v7.widget.DividerItemDecoration;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.DecodeFormat;
import com.bumptech.glide.request.RequestOptions;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import com.resou.reader.R;
import com.resou.reader.base.ResouBaseActivity;
import com.resou.reader.bookshelf.readhistory.datasupport.ReaderHistory;
import com.resou.reader.data.bookshelf.model.ReadRecord;
import com.resou.reader.data.local.LitePalHelper;
import com.resou.reader.mine.IView.UserInstance;
import com.resou.reader.reader.v.ReaderActivity;
import com.resou.reader.utils.DateUtils;
import com.resou.reader.utils.DynamicTimeFormat;
import com.resou.reader.utils.NetworkUtils;
import com.resou.reader.utils.ToastUtil;
import com.resou.reader.utils.eventbus.LoadBookEvent;
import com.resou.reader.utils.eventbus.MessageEvent;
import com.resou.reader.view.Loading;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.footer.ClassicsFooter;
import com.scwang.smartrefresh.layout.header.ClassicsHeader;
import com.scwang.smartrefresh.layout.listener.OnRefreshLoadMoreListener;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.net.ConnectException;
import java.net.UnknownHostException;
import java.net.UnknownServiceException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import java.util.concurrent.TimeoutException;

import butterknife.BindView;
import butterknife.ButterKnife;

public class ReadHistoryActivity extends ResouBaseActivity<ReadHistoryPresenter> implements IReadHistoryView {

    @BindView(R.id.recyclerView)
    RecyclerView recyclerView;
    @BindView(R.id.tv_title)
    TextView tvTitle;
    @BindView(R.id.toolbar)
    Toolbar toolbar;
    @BindView(R.id.no_book_layout)
    ConstraintLayout noBookLayout;
    @BindView(R.id.tv_right_btn)
    TextView tvRightBtn;
    @BindView(R.id.smart_refresh_layout)
    SmartRefreshLayout smartRefreshLayout;
    private HistoryAdapter mHistoryAdapter;
    private RecordAdapter mRecordAdapter;
    ClassicsFooter mClassicsFooter;
    int page = 0;

    public static void start(Context context) {
        Intent intent = new Intent(context, ReadHistoryActivity.class);
        context.startActivity(intent);
    }


    @Override
    public int getLayoutId() {
        return R.layout.activity_read_history;
    }

    @Override
    public void retryRefreshData() {

    }

    @Override
    protected void initStatusBar() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            getWindow().setStatusBarColor(getResources().getColor(R.color.colorAccent));
        }
        toolbar.setBackgroundColor(getResources().getColor(R.color.colorAccent));
        setSupportActionBar(toolbar);
        ActionBar actionBar = getSupportActionBar();
        if (actionBar != null) {
            actionBar.setDisplayHomeAsUpEnabled(true);
            actionBar.setDisplayShowTitleEnabled(false);
        }
    }

    @Override
    protected void initPresenter() {
        mPresenter = new ReadHistoryPresenter(this);
    }

    private Drawable mDrawableProgress;
    private ClassicsHeader mClassicsHeader;
    private boolean isLoadingMore = true;

    @Override
    protected void initView() {
        tvTitle.setText("阅读足迹");
        tvRightBtn.setText("清空");
        tvRightBtn.setVisibility(View.VISIBLE);
        mClassicsHeader = (ClassicsHeader) smartRefreshLayout.getRefreshHeader();
        mClassicsFooter = (ClassicsFooter) smartRefreshLayout.getRefreshFooter();
        mClassicsHeader.setLastUpdateTime(new Date(System.currentTimeMillis()));
        mClassicsHeader.setTimeFormat(new SimpleDateFormat("更新于 MM-dd HH:mm", Locale.CHINA));
        mClassicsHeader.setTimeFormat(new DynamicTimeFormat("更新于 %s"));
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
        }
        mDrawableProgress = ((ImageView) mClassicsHeader.findViewById(ClassicsHeader.ID_IMAGE_PROGRESS)).getDrawable();
        if (mDrawableProgress instanceof LayerDrawable) {
            mDrawableProgress = ((LayerDrawable) mDrawableProgress).getDrawable(0);
        }


        smartRefreshLayout.getLayout().setBackgroundResource(android.R.color.transparent);

        smartRefreshLayout.setPrimaryColors(0, 0xff666666);
        if (Build.VERSION.SDK_INT >= 21) {
            mDrawableProgress.setTint(0xff666666);
        } else if (mDrawableProgress instanceof VectorDrawableCompat) {
            ((VectorDrawableCompat) mDrawableProgress).setTint(0xff666666);
        }

        String token = UserInstance.getToken();
        tvRightBtn.setOnClickListener(v -> {
            if (NetworkUtils.isNetworkConnected(this)) {
                if (UserInstance.isLogin()) {
                    page = 0;
                    mPresenter.clearRemoteHistory(token);
                } else {
                    mPresenter.clearLocalHistory();
                }
                EventBus.getDefault().post(new LoadBookEvent());
            } else {
                ToastUtil.makeShortToast("网络异常");
            }
        });
        LinearLayoutManager layoutManager = new LinearLayoutManager(this);
        recyclerView.setLayoutManager(layoutManager);
        recyclerView.addItemDecoration(new DividerItemDecoration(this, LinearLayoutManager.VERTICAL));
        mRecordAdapter = new RecordAdapter(R.layout.item_read_history, null);
        mRecordAdapter.openLoadAnimation(BaseQuickAdapter.SCALEIN);
        recyclerView.setAdapter(mRecordAdapter);
        smartRefreshLayout.setOnLoadMoreListener(new OnRefreshLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                page++;
                mPresenter.loadRemoteRecord(token, page);
            }

            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                page = 0;
                if (NetworkUtils.isNetworkConnected(ReadHistoryActivity.this)) {
                    mPresenter.loadRemoteRecord(UserInstance.getToken(), page);
                } else {
                    ToastUtil.makeShortToast("网络异常");
                    //查询本地列表
                    mPresenter.queryReadHistory();
                    finishRefresh();
                }
            }
        });
    }

    private int LOAD_FROM = 0;
    private int LOAD_REMOTE = 1;
    private int LOAD_LOCAL = 2;

    private static final String TAG = "ReadHistoryActivity-App";


    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(LoadBookEvent event) {
        recyclerView.smoothScrollToPosition(0);
        page = 0;
        if (NetworkUtils.isNetworkConnected(ReadHistoryActivity.this)) {
            mPresenter.loadRemoteRecord(UserInstance.getToken(), page);
        } else {
            //查询本地列表
            mPresenter.queryReadHistory();
            finishRefresh();
        }
        smartRefreshLayout.setNoMoreData(false);
    }

    @Override
    public void setReadHistory(List<ReaderHistory> readHistory) {
        if (!NetworkUtils.isNetworkConnected(this)) {
            ToastUtil.makeShortToast("网络异常");
        }
        mHistoryAdapter = new HistoryAdapter(R.layout.item_read_history, null);
        if (readHistory != null && readHistory.size() > 0) {
            tvRightBtn.setVisibility(View.VISIBLE);
            noBookLayout.setVisibility(View.GONE);
            recyclerView.setVisibility(View.VISIBLE);
        } else {
            tvRightBtn.setVisibility(View.GONE);
            noBookLayout.setVisibility(View.VISIBLE);
            recyclerView.setVisibility(View.GONE);
        }
        LOAD_FROM = LOAD_LOCAL;
        mHistoryAdapter.clear();
        recyclerView.setAdapter(mHistoryAdapter);
        mHistoryAdapter.setNewData(readHistory);

    }

    @Override
    public void addReadHistory(List<ReaderHistory> readHistory) {

        if (mHistoryAdapter != null) {
            mHistoryAdapter.addData(readHistory);
        }
        isLoadingMore = false;
    }

    @Override
    public void setRemoteRecord(List<ReadRecord.ReadRecordBean> remoteRecord) {
        if (page == 0) {
            if (remoteRecord != null && remoteRecord.size() > 0) {
                tvRightBtn.setVisibility(View.VISIBLE);
                noBookLayout.setVisibility(View.GONE);
                recyclerView.setVisibility(View.VISIBLE);
            } else {
                tvRightBtn.setVisibility(View.GONE);
                noBookLayout.setVisibility(View.VISIBLE);
                recyclerView.setVisibility(View.GONE);
            }
            mRecordAdapter.setNewData(remoteRecord);
        } else {
            mRecordAdapter.addData(remoteRecord);
        }
    }

    @Override
    public void finishRefresh() {
        smartRefreshLayout.finishRefresh();
    }

    @Override
    public SmartRefreshLayout getSmartRefreshLayout() {
        return smartRefreshLayout;
    }

    @Override
    public void initData() {
        if (NetworkUtils.isNetworkConnected(this)) {
            //查询网络足迹
            mPresenter.loadRemoteRecord(UserInstance.getToken(), page);
        } else {
            //查询本地列表
            mPresenter.queryReadHistory();
        }
    }

    @Override
    public void showContent() {

    }

    @Override
    public void showProgress() {

    }

    @Override
    public void showError(Throwable throwable) {
        smartRefreshLayout.finishRefresh();
        smartRefreshLayout.finishLoadMore();
//        ToastUtil.makeShortToast(throwable.getMessage());
//        if (page == 0) {
//            showNetErrorView(R.id.rlContent);
//        }
    }

    @Override
    public void showEmpty() {

    }

    class HistoryAdapter extends BaseQuickAdapter<ReaderHistory, BaseViewHolder> {
        public HistoryAdapter(int layoutResId, @Nullable List<ReaderHistory> data) {
            super(layoutResId, data);
        }

        public HistoryAdapter(@Nullable List<ReaderHistory> data) {
            super(data);
        }

        @Override
        protected void convert(BaseViewHolder helper, ReaderHistory item) {
            ImageView imageView = helper.getView(R.id.history_book_poster);
            Glide.with(mContext).setDefaultRequestOptions(new RequestOptions().format(DecodeFormat.PREFER_RGB_565)).load(item.getPicUrl()).into(imageView);
            helper.setText(R.id.history_book_name, item.getName())
                    .setText(R.id.history_chapter_name, getString(R.string.history_chapter_name) + item.getHistoryChapterName())
                    .setText(R.id.history_time, getString(R.string.history_time) + DateUtils.transferLongToDate("yyyy年MM月dd日 HH:mm", item.getUserUpdateTime()));
            helper.getView(R.id.mHistoryOnclick).setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    ReaderActivity.startActivity(ReadHistoryActivity.this, item);
                }
            });
        }

        private void clear() {
            getData().clear();
            notifyDataSetChanged();
        }
    }

    class RecordAdapter extends BaseQuickAdapter<ReadRecord.ReadRecordBean, BaseViewHolder> {

        public RecordAdapter(int layoutResId, @Nullable List<ReadRecord.ReadRecordBean> data) {
            super(layoutResId, data);
        }

        public RecordAdapter(@Nullable List<ReadRecord.ReadRecordBean> data) {
            super(data);
        }

        @Override
        protected void convert(BaseViewHolder helper, ReadRecord.ReadRecordBean item) {
            ImageView imageView = helper.getView(R.id.history_book_poster);
            Glide.with(mContext).setDefaultRequestOptions(new RequestOptions().format(DecodeFormat.PREFER_RGB_565)).load(item.getCoverUrl()).into(imageView);
            helper.setText(R.id.history_book_name, item.getNovelName())
                    .setText(R.id.history_chapter_name, getString(R.string.history_chapter_name) + item.getChapterName())
                    .setText(R.id.history_time, getString(R.string.history_time) + DateUtils.transferLongToDate("yyyy年MM月dd日 HH:mm", (long) item.getReadTimeMs() * 1000));
            helper.getView(R.id.mHistoryOnclick).setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    ReaderHistory readerHistory = LitePalHelper.loadReadHistory(item.getNovelId());
                    readerHistory.setDescription(item.getDescription() + "");
                    ReaderActivity.startActivity(ReadHistoryActivity.this, readerHistory);
                }
            });
        }

        private void clear() {
            getData().clear();
            notifyDataSetChanged();
        }
    }

    static class RecordHolder extends RecyclerView.ViewHolder {

        @BindView(R.id.history_book_poster)
        ImageView historyBookPoster;
        @BindView(R.id.history_book_name)
        TextView historyBookName;
        @BindView(R.id.history_chapter_name)
        TextView historyChapterName;
        @BindView(R.id.history_time)
        TextView historyTime;

        RecordHolder(@NonNull View itemView) {
            super(itemView);
            ButterKnife.bind(this, itemView);
            historyBookName.getPaint().setFakeBoldText(true);
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().unregister(this);
        }
    }
}
